package com.leetcode.code

import java.util.HashMap

class LeetCode001Kotlin {

    var nums: IntArray = intArrayOf(2, 7, 11, 15)

    var target = 9

    /**
     * 自己的做法
     * 方法一
     */
    fun twosun3(): IntArray {
        val result: IntArray = IntArray(2)

        loop1@ for ((fristIndex, num) in nums.withIndex()) {

            loop2@ for ((index, num2) in nums.withIndex()) {
                if (fristIndex != index && (num + num2) == target) {
                    result[0] = fristIndex
                    result[1] = index
                    break@loop1
                }
            }
        }
        return result
    }

    /**
     * 自己
     * 方法二
     * 两遍哈希表
     */
    fun twoSumMe2(): IntArray {
        val map = HashMap<Int, Int>()
        for ((index, num) in nums.withIndex()) {
            map[num] = index
        }
        for ((index, num) in nums.withIndex()) {
            val com = target - num
            if (map.contains(com) && map[com] != index) return intArrayOf(index, map[com]!!)
        }

        throw IllegalArgumentException("No two sum solution")
    }

    /**`
     * 官方 方法一
     * 暴力法
     */
    fun twoSum(/*nums: IntArray, target: IntArray*/): IntArray {
        for (i in nums.indices) {
            for (j in i + 1 until nums.size) {
                if (nums[j] == target - nums[i]) {
                    return intArrayOf(i, j)
                }
            }
        }
        throw IllegalArgumentException("No two sum solution")
    }

    /**
     * 官方方法二
     * 两遍哈希表
     */
    fun twosum2(): IntArray {
        val map = java.util.HashMap<Int, Int>()
        for (i in nums.indices) {
            map[nums[i]] = i
        }
        for (i in nums.indices) {
            val complement = target - nums[i]
            if (map.containsKey(complement) && map[complement] != i) {
                return intArrayOf(i, map[complement]!!)
            }
        }
        throw IllegalArgumentException("No two sum solution")
    }
}

fun main() {
}